package com.sercomm.ott.mediaplayer.viewpager_test;

import android.util.Log;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;

/**
 * Created by davis on 17-11-3.
 */

public class HttpUtil {
    private static final String TAG = "httputil";
    private static final String NEXT_PAGE = "http://192.168.1.1/cgi-bin/next_page.json";
    private static final String AUTO = "http://192.168.1.1/cgi-bin/auto.json";
    private static final String REGISTER = "http://192.168.1.1/cgi-bin/register.json";
    private static final String SET_WAN = "http://192.168.1.1/cgi-bin/set_wan.json";
    private static final String SET_PASSWORD = "http://192.168.1.1/cgi-bin/set_password.json";
    private static final String SET_VOIP = "http://192.168.1.1/cgi-bin/set_voip.json";
    public static String GetWithHttpClient(String jsonUrl){
        HttpURLConnection connection = null;
        String status=null;
        try {
            URL url = new URL(jsonUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(8000);
            connection.setReadTimeout(8000);
            if (connection.getResponseCode() == 200) {
                InputStream in = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                if(jsonUrl.equals(NEXT_PAGE)) {
                    status = parseJson(response.toString(), "status");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(connection!=null){
                connection.disconnect();
            }
            return status;
        }
    }
    private static String getStatus(String jsonData){
        Log.d(TAG,"-----getStatus "+jsonData);
        JSONObject jsonObject;
        try {
            jsonObject = new JSONObject(jsonData);
            String status = jsonObject.getString("status");
            return status;
        }catch (Exception e){
            e.printStackTrace();
        }
        return "error";
    }
    private static String parseJson(String jsonData,String name){
        JSONObject jsonObject;
        try {
            jsonObject = new JSONObject(jsonData);
            String result = jsonObject.getString(name);
            return result;
        }catch (Exception e){
            e.printStackTrace();
        }
        return "error";
    }

    public static String postWhithHttpClient(String jsonUrl){
        HttpURLConnection connection=null;
        String result = null;
        try {
            URL url = new URL(jsonUrl);
            connection = (HttpURLConnection)url.openConnection();
            connection.setConnectTimeout(100000);
            connection.setReadTimeout(100000);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setRequestProperty("Content-Type","application/json");
            connection.setRequestProperty("Connection", "Keep-Alive");

            JSONObject root = new JSONObject();
            if(jsonUrl.equals(SET_PASSWORD)) {
                root.put("password", "1111");
            }else if(jsonUrl.equals(SET_WAN)){
                root.put("VLAMMode","1");
                root.put("VLANIDMark","2");
                root.put("802-1pMark","3");
                root.put("ServiceMode","4");
                root.put("Username","5");
                root.put("Password","6");
                root.put("AddressingType","7");
                root.put("ExternalIPAddress","8");
                root.put("SubnetMask","9");
                root.put("DefaultGateway","10");
                root.put("DNSEnabled","11");
                root.put("DNSServers","12");
            }else if(jsonUrl.equals(SET_VOIP)){
                root.put("sipUsername","12");
                root.put("authUsername","34");
                root.put("authPassword","123456");
            }else if(jsonUrl.equals(AUTO)){
                root.put("type","auto"); //type:auto manual
            }else if(jsonUrl.equals(REGISTER)){
                root.put("type","PASSWORD");  //type:OUI_SN  PASSWORD
            }
            Log.d(TAG,"----root toString: "+root.toString());
            OutputStream outputStream = connection.getOutputStream();
            DataOutputStream out = new DataOutputStream(outputStream);
            out.writeBytes(root.toString());
            out.flush();
            out.close();
            /*
             outputStream.write(root.toString().getBytes());
             outputStream.flush();
             outputStream.close();*/
            //服务器返回数据
            if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        connection.getInputStream()));
                StringBuffer buffer = new StringBuffer();
                String str = null;
                while ((str = reader.readLine()) != null) {
                    buffer.append(str);
                }
                if (jsonUrl.equals(SET_PASSWORD) || jsonUrl.equals(SET_WAN) || jsonUrl.equals(SET_VOIP)) {
                    result = parseJson(buffer.toString(), "result");
                } else if (jsonUrl.equals(AUTO) || jsonUrl.equals(REGISTER)) {
                    result = parseJson(buffer.toString(), "type");
                }
                Log.d(TAG, "buffer is " + buffer.toString());
                reader.close();
            }else {
                Log.d(TAG,"------getResponseCode "+connection.getResponseCode());
            }
        }catch (SocketTimeoutException e){
            Log.d(TAG,"---socket time out");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            Log.d(TAG,"----disconnected");
            if(connection!=null){
                connection.disconnect();
            }
        }
        return result;
    }

    public static String postWhithHttpClient(String jsonUrl,JSONObject jsonObject){
        HttpURLConnection connection=null;
        //String result = null;
        StringBuffer buffer = new StringBuffer();
        try {
            URL url = new URL(jsonUrl);
            connection = (HttpURLConnection)url.openConnection();
            connection.setConnectTimeout(90000);
            connection.setReadTimeout(90000);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setRequestProperty("Content-Type","application/json");

            OutputStream outputStream = connection.getOutputStream();
            DataOutputStream out = new DataOutputStream(outputStream);
            out.writeBytes(jsonObject.toString());
            out.flush();
            out.close();

            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));

            String str = null;
            while ((str=reader.readLine()) !=null){
                buffer.append(str);
            }
            Log.d(TAG,"buffer is "+buffer.toString());
            reader.close();
        }catch (SocketTimeoutException e){
            Log.d(TAG,"---socket time out");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(connection!=null){
                connection.disconnect();
            }
            return buffer.toString();
        }
    }

    public static String postHttpResult(String jsonUrl,String postResult){
        String result = null;
        if(jsonUrl.equals(SET_PASSWORD) || jsonUrl.equals(SET_WAN) || jsonUrl.equals(SET_VOIP)) {
            result = parseJson(postResult,"result");
        }else if(jsonUrl.equals(AUTO) || jsonUrl.equals(REGISTER)){
            result = parseJson(postResult,"type");
        }
        return result;
    }

}
